<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{{.title}}</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 20px;
            background-color: #f5f5f5;
        }
        .container {
            max-width: 1400px;
            margin: 0 auto;
            background: white;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            overflow: hidden;
        }
        .header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 20px 30px;
            text-align: center;
        }
        .nav {
            text-align: center;
            padding: 15px;
            background: #f8f9fa;
            border-bottom: 1px solid #ddd;
        }
        .nav a {
            display: inline-block;
            margin: 0 10px;
            padding: 8px 16px;
            background: #6c757d;
            color: white;
            text-decoration: none;
            border-radius: 4px;
            font-size: 14px;
        }
        .nav a:hover {
            background: #5a6268;
        }
        .main-content {
            display: flex;
            min-height: 600px;
        }
        .sidebar {
            width: 300px;
            background: #f8f9fa;
            border-right: 1px solid #ddd;
            padding: 20px;
        }
        .content {
            flex: 1;
            padding: 20px;
        }
        .toolbar {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            padding: 15px;
            background: #f8f9fa;
            border-radius: 5px;
        }
        .search-box {
            display: flex;
            gap: 10px;
        }
        .search-box input {
            padding: 8px 12px;
            border: 1px solid #ddd;
            border-radius: 4px;
            width: 250px;
        }
        .btn {
            padding: 8px 16px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            text-decoration: none;
            display: inline-block;
            text-align: center;
        }
        .btn-primary {
            background: #007bff;
            color: white;
        }
        .btn-primary:hover {
            background: #0056b3;
        }
        .btn-success {
            background: #28a745;
            color: white;
        }
        .btn-success:hover {
            background: #218838;
        }
        .btn-warning {
            background: #ffc107;
            color: #212529;
        }
        .btn-warning:hover {
            background: #e0a800;
        }
        .btn-danger {
            background: #dc3545;
            color: white;
        }
        .btn-danger:hover {
            background: #c82333;
        }
        .btn-sm {
            padding: 4px 8px;
            font-size: 12px;
        }
        .category-tree {
            border: 1px solid #ddd;
            border-radius: 5px;
            max-height: 400px;
            overflow-y: auto;
            margin-bottom: 20px;
        }
        .tree-item {
            padding: 10px 12px;
            border-bottom: 1px solid #eee;
            cursor: pointer;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .tree-item:hover {
            background: #e3f2fd;
        }
        .tree-item.active {
            background: #2196f3;
            color: white;
        }
        .tree-item.level-1 {
            padding-left: 12px;
            font-weight: bold;
        }
        .tree-item.level-2 {
            padding-left: 32px;
        }
        .tree-item.level-3 {
            padding-left: 52px;
        }
        .bookmark-list {
            margin-top: 20px;
        }
        .bookmark-item {
            border: 1px solid #ddd;
            border-radius: 8px;
            padding: 15px;
            background: white;
            margin-bottom: 15px;
            transition: transform 0.2s, box-shadow 0.2s;
            position: relative;
        }
        .bookmark-item:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(0,0,0,0.15);
        }
        .bookmark-item.selected {
            border-color: #007bff;
            background: #f0f8ff;
        }
        .bookmark-header {
            display: flex;
            align-items: center;
            margin-bottom: 10px;
        }
        .bookmark-favicon {
            width: 20px;
            height: 20px;
            margin-right: 10px;
            border-radius: 3px;
        }
        .bookmark-title {
            font-weight: bold;
            color: #333;
            text-decoration: none;
            flex: 1;
        }
        .bookmark-title:hover {
            color: #007bff;
        }
        .bookmark-url {
            color: #666;
            font-size: 12px;
            margin-bottom: 8px;
            word-break: break-all;
        }
        .bookmark-description {
            color: #888;
            font-size: 13px;
            margin-bottom: 10px;
            line-height: 1.4;
        }
        .bookmark-meta {
            display: flex;
            justify-content: space-between;
            align-items: center;
            font-size: 12px;
            color: #999;
        }
        .bookmark-actions {
            position: absolute;
            top: 10px;
            right: 10px;
            opacity: 0;
            transition: opacity 0.2s;
        }
        .bookmark-item:hover .bookmark-actions {
            opacity: 1;
        }
        .checkbox {
            position: absolute;
            top: 10px;
            left: 10px;
        }
        .modal {
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0,0,0,0.5);
        }
        .modal-content {
            background-color: white;
            margin: 5% auto;
            padding: 20px;
            border-radius: 8px;
            width: 500px;
            max-width: 90%;
            max-height: 80%;
            overflow-y: auto;
        }
        .modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            padding-bottom: 10px;
            border-bottom: 1px solid #eee;
        }
        .close {
            font-size: 24px;
            cursor: pointer;
            color: #999;
        }
        .close:hover {
            color: #333;
        }
        .form-group {
            margin-bottom: 15px;
        }
        .form-group label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
        }
        .form-group input,
        .form-group select,
        .form-group textarea {
            width: 100%;
            padding: 8px 12px;
            border: 1px solid #ddd;
            border-radius: 4px;
            box-sizing: border-box;
        }
        .form-group textarea {
            height: 80px;
            resize: vertical;
        }
        .preview-info {
            background: #f8f9fa;
            padding: 10px;
            border-radius: 4px;
            margin-top: 10px;
            display: none;
        }
        .preview-info img {
            width: 16px;
            height: 16px;
            margin-right: 8px;
        }
        .message {
            padding: 10px;
            margin: 10px 0;
            border-radius: 4px;
            display: none;
        }
        .message.success {
            background: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        .message.error {
            background: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        .batch-actions {
            display: none;
            background: #fff3cd;
            border: 1px solid #ffeaa7;
            border-radius: 4px;
            padding: 10px;
            margin-bottom: 15px;
        }
        .empty-state {
            text-align: center;
            padding: 60px 20px;
            color: #999;
        }
        .empty-state i {
            font-size: 4rem;
            margin-bottom: 20px;
            display: block;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>{{.title}}</h1>
            <p>管理您的网址收藏</p>
        </div>
        
        <div class="nav">
            <a href="/">返回首页</a>
            <a href="/category">分类管理</a>
            <a href="/register">用户注册</a>
            <a href="/login">用户登录</a>
        </div>

        <div id="message" class="message"></div>

        <div class="main-content">
            <!-- 侧边栏 - 分类树 -->
            <div class="sidebar">
                <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px;">
                    <h3>分类</h3>
                    <button class="btn btn-sm btn-primary" onclick="loadCategoryTree()">刷新</button>
                </div>
                
                <div id="categoryTree" class="category-tree">
                    <div class="tree-item active" data-category-id="" onclick="selectCategory(null, '全部收藏')">
                        <span>📚 全部收藏</span>
                        <span id="totalCount">0</span>
                    </div>
                    <div class="tree-item" data-category-id="uncategorized" onclick="selectCategory('uncategorized', '未分类')">
                        <span>📁 未分类</span>
                        <span id="uncategorizedCount">0</span>
                    </div>
                </div>
            </div>

            <!-- 主内容区 -->
            <div class="content">
                <!-- 工具栏 -->
                <div class="toolbar">
                    <div>
                        <h3 id="currentCategoryName">全部收藏</h3>
                        <small class="text-muted" id="bookmarkCount">共 0 个收藏</small>
                    </div>
                    <div class="search-box">
                        <input type="text" id="searchInput" placeholder="搜索收藏...">
                        <button class="btn btn-primary" onclick="searchBookmarks()">搜索</button>
                        <button class="btn btn-success" onclick="showAddModal()">添加收藏</button>
                    </div>
                </div>

                <!-- 批量操作栏 -->
                <div id="batchActions" class="batch-actions">
                    <span>已选择 <span id="selectedCount">0</span> 个收藏</span>
                    <div style="float: right;">
                        <select id="batchMoveCategory" style="margin-right: 10px;">
                            <option value="">选择目标分类</option>
                        </select>
                        <button class="btn btn-sm btn-warning" onclick="batchMove()">移动到分类</button>
                        <button class="btn btn-sm btn-danger" onclick="batchDelete()">批量删除</button>
                        <button class="btn btn-sm" onclick="clearSelection()">取消选择</button>
                    </div>
                    <div style="clear: both;"></div>
                </div>

                <!-- 收藏列表 -->
                <div id="bookmarkList" class="bookmark-list">
                    <div class="empty-state">
                        <i>🔖</i>
                        <p>暂无收藏，点击"添加收藏"开始收藏您喜欢的网站</p>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 添加/编辑收藏模态框 -->
    <div id="bookmarkModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h3 id="modalTitle">添加收藏</h3>
                <span class="close" onclick="closeModal()">&times;</span>
            </div>
            <form id="bookmarkForm">
                <div class="form-group">
                    <label for="bookmarkUrl">网址 URL:</label>
                    <input type="url" id="bookmarkUrl" name="url" required placeholder="https://example.com">
                    <button type="button" class="btn btn-sm btn-primary" onclick="previewUrl()" style="margin-top: 5px;">获取预览</button>
                </div>
                
                <div id="previewInfo" class="preview-info">
                    <div style="display: flex; align-items: center;">
                        <img id="previewFavicon" src="" alt="">
                        <span id="previewTitle"></span>
                    </div>
                </div>

                <div class="form-group">
                    <label for="bookmarkTitle">标题:</label>
                    <input type="text" id="bookmarkTitle" name="title" required>
                </div>

                <div class="form-group">
                    <label for="bookmarkDescription">描述:</label>
                    <textarea id="bookmarkDescription" name="description" placeholder="可选"></textarea>
                </div>

                <div class="form-group">
                    <label for="bookmarkCategory">分类:</label>
                    <select id="bookmarkCategory" name="category_id">
                        <option value="">无分类</option>
                    </select>
                </div>

                <div style="text-align: right;">
                    <button type="button" class="btn" onclick="closeModal()">取消</button>
                    <button type="submit" class="btn btn-primary">保存</button>
                </div>
            </form>
        </div>
    </div>

    <script>
        const API_BASE = '/api';
        let currentCategoryId = null;
        let currentSearch = '';
        let isEditMode = false;
        let editBookmarkId = null;
        let selectedBookmarks = new Set();
        let authToken = localStorage.getItem('jwt_token') || '';

        // 获取认证头
        function getAuthHeaders() {
            const headers = {
                'Content-Type': 'application/json'
            };
            if (authToken) {
                headers['Authorization'] = 'Bearer ' + authToken;
            }
            return headers;
        }
        let allBookmarks = []; // 存储所有收藏数据

        // 检查认证状态
        function checkAuth() {
            if (!authToken) {
                showMessage('请先登录', 'error');
                setTimeout(() => {
                    window.location.href = '/login';
                }, 2000);
                return false;
            }
            return true;
        }

        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', function() {
            if (!checkAuth()) return;

            loadCategoryTree();
            loadAllBookmarks(); // 加载所有收藏
        });

        // 显示消息
        function showMessage(message, type) {
            const messageDiv = document.getElementById('message');
            messageDiv.className = `message ${type}`;
            messageDiv.textContent = message;
            messageDiv.style.display = 'block';
            
            setTimeout(() => {
                messageDiv.style.display = 'none';
            }, 3000);
        }

        // 加载分类树
        async function loadCategoryTree() {
            try {
                const response = await fetch(`${API_BASE}/category/tree`, {
                    headers: getAuthHeaders()
                });
                const data = await response.json();
                
                if (data.code === 200) {
                    renderCategoryTree(data.data);
                    loadCategoryOptions(data.data);
                } else {
                    console.error('加载分类树失败:', data.message);
                }
            } catch (error) {
                console.error('加载分类树失败:', error);
            }
        }

        // 渲染分类树
        function renderCategoryTree(categories) {
            const treeDiv = document.getElementById('categoryTree');
            let html = `
                <div class="tree-item ${currentCategoryId === null ? 'active' : ''}" data-category-id="" onclick="selectCategory(null, '全部收藏')">
                    <span>📚 全部收藏</span>
                    <span id="totalCount">0</span>
                </div>
                <div class="tree-item ${currentCategoryId === 'uncategorized' ? 'active' : ''}" data-category-id="uncategorized" onclick="selectCategory('uncategorized', '未分类')">
                    <span>📁 未分类</span>
                    <span id="uncategorizedCount">0</span>
                </div>
            `;

            function renderNode(node, level = 1) {
                const isActive = currentCategoryId === node.id;
                html += `
                    <div class="tree-item level-${level} ${isActive ? 'active' : ''}" data-category-id="${node.id}" onclick="selectCategory(${node.id}, '${node.name}')">
                        <span>${'📂'.repeat(level)} ${node.name}</span>
                        <span id="count-${node.id}">0</span>
                    </div>
                `;
                if (node.children && node.children.length > 0) {
                    node.children.forEach(child => renderNode(child, level + 1));
                }
            }

            if (categories && categories.length > 0) {
                categories.forEach(category => renderNode(category));
            }

            treeDiv.innerHTML = html;
        }

        // 选择分类
        function selectCategory(categoryId, categoryName) {
            currentCategoryId = categoryId === 'uncategorized' ? null : categoryId;
            
            // 更新UI
            document.getElementById('currentCategoryName').textContent = categoryName;
            document.getElementById('searchInput').value = '';
            
            // 更新分类树选中状态
            document.querySelectorAll('.tree-item').forEach(item => {
                item.classList.remove('active');
            });
            
            if (categoryId === null) {
                document.querySelector('[data-category-id=""]').classList.add('active');
            } else if (categoryId === 'uncategorized') {
                document.querySelector('[data-category-id="uncategorized"]').classList.add('active');
            } else {
                document.querySelector(`[data-category-id="${categoryId}"]`).classList.add('active');
            }
            
            filterBookmarks(); // 根据分类筛选收藏
        }

        // 加载所有收藏
        async function loadAllBookmarks() {
            try {
                const response = await fetch(`${API_BASE}/bookmark`, {
                    headers: getAuthHeaders()
                });
                const data = await response.json();
                
                if (data.code === 200) {
                    allBookmarks = data.data;
                    filterBookmarks();
                } else {
                    showMessage(data.message, 'error');
                }
            } catch (error) {
                showMessage('加载收藏失败', 'error');
            }
        }

        // 筛选并显示收藏
        function filterBookmarks() {
            let filteredBookmarks = [...allBookmarks];
            
            // 根据分类筛选
            if (currentCategoryId !== null) {
                if (currentCategoryId === 'uncategorized') {
                    // 筛选未分类的收藏（category_id为null）
                    filteredBookmarks = filteredBookmarks.filter(bookmark => !bookmark.category_id);
                } else {
                    filteredBookmarks = filteredBookmarks.filter(bookmark => 
                        bookmark.category_id === currentCategoryId);
                }
            }
            
            // 根据搜索关键词筛选
            if (currentSearch) {
                const keyword = currentSearch.toLowerCase();
                filteredBookmarks = filteredBookmarks.filter(bookmark => 
                    bookmark.title.toLowerCase().includes(keyword) ||
                    bookmark.url.toLowerCase().includes(keyword) ||
                    (bookmark.description && bookmark.description.toLowerCase().includes(keyword))
                );
            }
            
            renderBookmarks(filteredBookmarks);
            updateBookmarkCount(filteredBookmarks.length);
        }

        // 渲染收藏列表
        function renderBookmarks(bookmarks) {
            const list = document.getElementById('bookmarkList');
            
            if (!bookmarks || bookmarks.length === 0) {
                list.innerHTML = `
                    <div class="empty-state">
                        <i>🔖</i>
                        <p>暂无收藏数据</p>
                    </div>
                `;
                return;
            }

            let html = '';
            bookmarks.forEach(bookmark => {
                const isSelected = selectedBookmarks.has(bookmark.id);
                html += `
                    <div class="bookmark-item ${isSelected ? 'selected' : ''}" data-id="${bookmark.id}">
                        <input type="checkbox" class="checkbox" ${isSelected ? 'checked' : ''} onchange="toggleBookmarkSelection(${bookmark.id})">
                        
                        <div class="bookmark-actions">
                            <button class="btn btn-sm btn-warning" onclick="editBookmark(${bookmark.id})">编辑</button>
                            <button class="btn btn-sm btn-danger" onclick="deleteBookmark(${bookmark.id})">删除</button>
                        </div>

                        <div class="bookmark-header">
                            ${bookmark.favicon ? `<img src="${bookmark.favicon}" class="bookmark-favicon" onerror="this.style.display='none'">` : ''}
                            <a href="${bookmark.url}" class="bookmark-title" target="_blank" onclick="visitBookmark(${bookmark.id})">${bookmark.title}</a>
                        </div>

                        <div class="bookmark-url">${bookmark.url}</div>
                        
                        ${bookmark.description ? `<div class="bookmark-description">${bookmark.description}</div>` : ''}

                        <div class="bookmark-meta">
                            <span>${bookmark.category ? bookmark.category.name : '未分类'}</span>
                            <span>访问 ${bookmark.visit_count} 次</span>
                        </div>
                    </div>
                `;
            });

            list.innerHTML = html;
        }

        // 更新收藏数量
        function updateBookmarkCount(total) {
            document.getElementById('bookmarkCount').textContent = `共 ${total} 个收藏`;
        }

        // 搜索收藏
        function searchBookmarks() {
            currentSearch = document.getElementById('searchInput').value.trim();
            filterBookmarks();
        }

        // 显示添加收藏模态框
        function showAddModal() {
            isEditMode = false;
            editBookmarkId = null;
            document.getElementById('modalTitle').textContent = '添加收藏';
            document.getElementById('bookmarkForm').reset();
            document.getElementById('previewInfo').style.display = 'none';
            document.getElementById('bookmarkModal').style.display = 'block';
            loadCategoryTree(); // 刷新分类选项
        }

        // 编辑收藏
        async function editBookmark(id) {
            try {
                const response = await fetch(`${API_BASE}/bookmark/${id}`, {
                    headers: getAuthHeaders()
                });
                const data = await response.json();
                
                if (data.code === 200) {
                    const bookmark = data.data;
                    isEditMode = true;
                    editBookmarkId = id;
                    
                    document.getElementById('modalTitle').textContent = '编辑收藏';
                    document.getElementById('bookmarkUrl').value = bookmark.url;
                    document.getElementById('bookmarkTitle').value = bookmark.title;
                    document.getElementById('bookmarkDescription').value = bookmark.description || '';
                    document.getElementById('bookmarkCategory').value = bookmark.category_id || '';
                    
                    document.getElementById('bookmarkModal').style.display = 'block';
                } else {
                    showMessage(data.message, 'error');
                }
            } catch (error) {
                showMessage('获取收藏信息失败', 'error');
            }
        }

        // 删除收藏
        async function deleteBookmark(id) {
            if (!confirm('确定要删除这个收藏吗？')) {
                return;
            }

            try {
                const response = await fetch(`${API_BASE}/bookmark/${id}`, {
                    method: 'DELETE',
                    headers: getAuthHeaders()
                });
                const data = await response.json();
                
                if (data.code === 200) {
                    showMessage('删除成功', 'success');
                    // 从allBookmarks中移除已删除的收藏
                    allBookmarks = allBookmarks.filter(bookmark => bookmark.id !== id);
                    filterBookmarks();
                } else {
                    showMessage(data.message, 'error');
                }
            } catch (error) {
                showMessage('删除失败', 'error');
            }
        }

        // 获取网址预览
        async function previewUrl() {
            const url = document.getElementById('bookmarkUrl').value.trim();
            if (!url) {
                showMessage('请先输入网址', 'error');
                return;
            }

            try {
                const response = await fetch(`${API_BASE}/bookmark/preview?url=${encodeURIComponent(url)}`, {
                    headers: getAuthHeaders()
                });
                const data = await response.json();
                
                if (data.code === 200) {
                    const preview = data.data;
                    document.getElementById('previewTitle').textContent = preview.title;
                    document.getElementById('previewFavicon').src = preview.favicon;
                    document.getElementById('previewInfo').style.display = 'block';
                    
                    // 自动填充标题
                    if (!document.getElementById('bookmarkTitle').value) {
                        document.getElementById('bookmarkTitle').value = preview.title;
                    }
                } else {
                    showMessage(data.message, 'error');
                }
            } catch (error) {
                showMessage('获取预览失败', 'error');
            }
        }

        // 访问收藏
        async function visitBookmark(id) {
            try {
                await fetch(`${API_BASE}/bookmark/${id}/visit`, {
                    method: 'POST',
                    headers: getAuthHeaders()
                });
            } catch (error) {
                console.error('记录访问失败:', error);
            }
        }

        // 切换收藏选择状态
        function toggleBookmarkSelection(id) {
            if (selectedBookmarks.has(id)) {
                selectedBookmarks.delete(id);
            } else {
                selectedBookmarks.add(id);
            }
            
            updateBatchActions();
            updateBookmarkItemSelection(id);
        }

        // 更新收藏项选择状态
        function updateBookmarkItemSelection(id) {
            const item = document.querySelector(`[data-id="${id}"]`);
            if (item) {
                if (selectedBookmarks.has(id)) {
                    item.classList.add('selected');
                } else {
                    item.classList.remove('selected');
                }
            }
        }

        // 更新批量操作栏
        function updateBatchActions() {
            const batchActions = document.getElementById('batchActions');
            const selectedCount = selectedBookmarks.size;
            
            if (selectedCount > 0) {
                batchActions.style.display = 'block';
                document.getElementById('selectedCount').textContent = selectedCount;
            } else {
                batchActions.style.display = 'none';
            }
        }

        // 清除选择
        function clearSelection() {
            selectedBookmarks.clear();
            document.querySelectorAll('.bookmark-item').forEach(item => {
                item.classList.remove('selected');
                const checkbox = item.querySelector('.checkbox');
                if (checkbox) checkbox.checked = false;
            });
            updateBatchActions();
        }

        // 批量删除
        async function batchDelete() {
            if (selectedBookmarks.size === 0) {
                showMessage('请先选择要删除的收藏', 'error');
                return;
            }

            if (!confirm(`确定要删除选中的 ${selectedBookmarks.size} 个收藏吗？`)) {
                return;
            }

            try {
                const response = await fetch(`${API_BASE}/bookmark/batch`, {
                    method: 'POST',
                    headers: getAuthHeaders(),
                    body: JSON.stringify({
                        bookmark_ids: Array.from(selectedBookmarks),
                        action: 'delete'
                    })
                });
                
                const data = await response.json();
                
                if (data.code === 200) {
                    showMessage('批量删除成功', 'success');
                    // 从allBookmarks中移除已删除的收藏
                    allBookmarks = allBookmarks.filter(bookmark => !selectedBookmarks.has(bookmark.id));
                    clearSelection();
                    filterBookmarks();
                } else {
                    showMessage(data.message, 'error');
                }
            } catch (error) {
                showMessage('批量删除失败', 'error');
            }
        }

        // 批量移动
        async function batchMove() {
            if (selectedBookmarks.size === 0) {
                showMessage('请先选择要移动的收藏', 'error');
                return;
            }

            const targetCategoryId = document.getElementById('batchMoveCategory').value;
            
            try {
                const response = await fetch(`${API_BASE}/bookmark/batch`, {
                    method: 'POST',
                    headers: getAuthHeaders(),
                    body: JSON.stringify({
                        bookmark_ids: Array.from(selectedBookmarks),
                        action: 'move',
                        category_id: targetCategoryId ? parseInt(targetCategoryId) : null
                    })
                });
                
                const data = await response.json();
                
                if (data.code === 200) {
                    showMessage('批量移动成功', 'success');
                    // 更新allBookmarks中的分类信息
                    allBookmarks.forEach(bookmark => {
                        if (selectedBookmarks.has(bookmark.id)) {
                            bookmark.category_id = targetCategoryId ? parseInt(targetCategoryId) : null;
                            // 更新分类名称
                            if (targetCategoryId) {
                                // 查找新分类名称
                                const newCategory = findCategoryById(targetCategoryId);
                                if (newCategory) {
                                    bookmark.category = newCategory;
                                }
                            } else {
                                bookmark.category = null;
                            }
                        }
                    });
                    clearSelection();
                    filterBookmarks();
                } else {
                    showMessage(data.message, 'error');
                }
            } catch (error) {
                showMessage('批量移动失败', 'error');
            }
        }

        // 根据ID查找分类
        function findCategoryById(categoryId) {
            // 这里需要实现查找分类的逻辑，暂时返回null
            return null;
        }

        // 加载分类选项
        function loadCategoryOptions(categories) {
            const selects = [document.getElementById('bookmarkCategory'), document.getElementById('batchMoveCategory')];
            
            selects.forEach(select => {
                if (!select) return;
                
                const isBookmarkCategory = select.id === 'bookmarkCategory';
                select.innerHTML = isBookmarkCategory ? '<option value="">无分类</option>' : '<option value="">移动到根目录</option>';
                
                function addOptions(cats, prefix = '') {
                    cats.forEach(cat => {
                        select.innerHTML += `<option value="${cat.id}">${prefix}${cat.name}</option>`;
                        if (cat.children && cat.children.length > 0) {
                            addOptions(cat.children, prefix + '　');
                        }
                    });
                }
                
                if (categories && categories.length > 0) {
                    addOptions(categories);
                }
            });
        }

        // 关闭模态框
        function closeModal() {
            document.getElementById('bookmarkModal').style.display = 'none';
        }

        // 表单提交
        document.getElementById('bookmarkForm').addEventListener('submit', async function(e) {
            e.preventDefault();
            
            const url = document.getElementById('bookmarkUrl').value.trim();
            const title = document.getElementById('bookmarkTitle').value.trim();
            const description = document.getElementById('bookmarkDescription').value.trim();
            const categoryId = document.getElementById('bookmarkCategory').value;
            
            if (!url || !title) {
                showMessage('网址和标题不能为空', 'error');
                return;
            }

            const requestData = {
                url: url,
                title: title,
                description: description,
                category_id: categoryId ? parseInt(categoryId) : null
            };

            try {
                let response;
                if (isEditMode) {
                    response = await fetch(`${API_BASE}/bookmark/${editBookmarkId}`, {
                        method: 'PUT',
                        headers: getAuthHeaders(),
                        body: JSON.stringify(requestData)
                    });
                } else {
                    response = await fetch(`${API_BASE}/bookmark/`, {
                        method: 'POST',
                        headers: getAuthHeaders(),
                        body: JSON.stringify(requestData)
                    });
                }
                
                const data = await response.json();
                
                if (data.code === 200) {
                    showMessage(isEditMode ? '更新成功' : '添加成功', 'success');
                    closeModal();
                    // 重新加载所有收藏
                    loadAllBookmarks();
                } else {
                    showMessage(data.message, 'error');
                }
            } catch (error) {
                showMessage(isEditMode ? '更新失败' : '添加失败', 'error');
            }
        });

        // 回车搜索
        document.getElementById('searchInput').addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                searchBookmarks();
            }
        });

        // 点击模态框外部关闭
        window.onclick = function(event) {
            const modal = document.getElementById('bookmarkModal');
            if (event.target === modal) {
                closeModal();
            }
        }
    </script>
</body>
</html>